<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\read_uv;


use app\common\model\book\Book;
use app\common\model\book\Category;
use app\common\model\book\Chapter;
use app\common\model\read_uv\ReadUv;
use app\common\logic\BaseLogic;
use app\common\service\FileService;
use think\facade\Db;


/**
 * ReadUv逻辑
 * Class ReadUvLogic
 * @package app\adminapi\logic
 */
class ReadUvLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/04/22 15:52
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            ReadUv::create([
                'date' => $params['date'],
                'platform' => $params['platform'],
                'book_id' => $params['book_id'],
                'book_name' => $params['book_name'],
                'chapter_id' => $params['chapter_id'],
                'chapter_name' => $params['chapter_name'],
                'read_uv' => $params['read_uv'],
                'new_user_read_uv' => $params['new_user_read_uv']
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/04/22 15:52
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            ReadUv::where('id', $params['id'])->update([
                'date' => $params['date'],
                'platform' => $params['platform'],
                'book_id' => $params['book_id'],
                'book_name' => $params['book_name'],
                'chapter_id' => $params['chapter_id'],
                'chapter_name' => $params['chapter_name'],
                'read_uv' => $params['read_uv'],
                'new_user_read_uv' => $params['new_user_read_uv']
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/04/22 15:52
     */
    public static function delete(array $params): bool
    {
        return ReadUv::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/04/22 15:52
     */
    public static function detail($params): array
    {
        return ReadUv::findOrEmpty($params['id'])->toArray();
    }

    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/04/22 15:52
     */
    public static function bookUvDetail($params): array
    {
        $result = Book::where('id',$params['book_id'])->field('id,book_name,thumb,intro,author,fullflag,book_type,pricetype,thousand_word_price,sort_id')->findOrEmpty()->toArray();
        if (!empty($result)){
            $result['sort_name'] = Category::where('id',$result['sort_id'])->value('name')??'';
            $result['thumb'] = FileService::getFileUrl($result['thumb']);
//            $result['chapter_list'] = self::getChapterUvList($params['book_id'],$params['platform']);
            $chapterList = Chapter::suffix(getSuffix($params['book_id']))->where('book_id',$params['book_id'])
                ->field(['chapter_id','book_id','chapter_name','book_name','is_vip','chapter_order'])
                ->order(['chapter_order' => 'asc'])
                ->select()
                ->toArray();
            $chapterUvList = ReadUv::where(['book_id'=>$params['book_id'],'platform'=>$params['platform']])
                ->field(['chapter_id','book_id','chapter_order','sum(read_uv) as read_uv','sum(new_user_read_uv) as new_user_read_uv'])
                ->group('chapter_order')
                ->order(['chapter_order' => 'asc'])
                ->select()
                ->toArray();
            // 假设章节列表数组为$chapterList，章节UV列表数组为$chapterUvList
            foreach ($chapterList as &$chapter) {
                $found = false; // 标记是否找到匹配的章节UV记录
                foreach ($chapterUvList as $chapterUv) {
                    if ($chapterUv['book_id'] == $chapter['book_id'] && $chapterUv['chapter_id'] == $chapter['chapter_id']) {
                        $chapter['read_uv'] = $chapterUv['read_uv'];
                        $chapter['new_user_read_uv'] = $chapterUv['new_user_read_uv'];
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    $chapter['read_uv'] = 0;
                    $chapter['new_user_read_uv'] = 0;
                }
                if ($chapter['chapter_order']==1){
                    $result['book_uv'] = $chapter['read_uv'];
                }
            }
            $result['chapter_list'] = $chapterList;
        }
        return $result;
    }
//    public static function getChapterUvList($book_id,$platform)
//    {
//
//        return $chapterList;
//
//    }
}